#include "stdafx.h"
using namespace std;
Mod_Surface_water::Mod_Surface_water(Mod_in *iinp):Mod_out_handling(iinp){;}
Mod_Surface_water::~Mod_Surface_water(){;}
int Mod_Surface_water::compute(time_intervall &ti){}
Mod_Surface_water_simple::Mod_Surface_water_simple(map <string,int> &iIO_options,
                         Mod_in *iinp,
                         Inp_weather *iweather,
                         Mod_ETP *imod_etp,
                         Mod_Interception *imod_interception,
                         Mod_Snow *imod_snow,
                         Mod_wc *imod_wc
                ):Mod_Surface_water(iinp)
{
		//1. switches setzen
		IO_options=iIO_options;
	
		//3. Default Parameter setzen
		STORMAX=1000; 
		
		
	    //4. Modelle verkn�pfen
	    inp_weather= iweather;
		mod_etp=imod_etp;
		mod_interception=imod_interception;
		mod_snow=imod_snow;
		mod_wc=imod_wc;
		
		//5. Output_kategorien f�r diese Variante setzen!!
		out->fluxes.set_key("P_Infiltration");			//[mm/d]
		out->fluxes.set_key("ETR_Surface_water");		//[mm/d]
		out->fluxes.set_key("Surface_Lateral_out");    //[mm/d]
		
		
		timepointmap <double> ntmap (inp->tempgrid);
		 out->states["Surface_Storage"]=ntmap;	 //[mm]
		 out->states["Surface_Storage_without_infiltration"]=ntmap;	 //[mm]
    
}
int Mod_Surface_water_simple::compute(time_intervall &ti)
{
	double budget;
        timestamp start=ti.get_start();
        timestamp end=ti.get_end();
	double last_storage=this->get_states("Surface_Storage",start);	  //[mm]
	double throughfall=this->mod_interception->get_fluxes("P_Throughfall",ti);	   //[mm/d]
	double input_from_melt=this->mod_snow->get_fluxes("Snow_melt",ti);	 //[mm/d]
	//double potential_infiltration=this->mod_wc->get_states("Potential_Infiltration",ti);  // [mm]
	
	
	double recent_storage=last_storage-this->mod_etp->get_fluxes("ETR_Surface_water",ti)*ti.get_dur();		 //[mm]
	recent_storage = recent_storage+(input_from_melt+throughfall)*ti.get_dur();			 //[mm]
	this->set_states("Surface_Storage_without_infiltration",end,recent_storage); //[mm]
	
	double real_infiltration=this->mod_wc->get_fluxes("Real_Infiltration",ti);  // [mm/d]
	
	recent_storage=max(0.0,recent_storage-real_infiltration*ti.get_dur());		//[mm]
	
	
	this->set_states("Surface_Storage",end,recent_storage);
	
	budget=recent_storage-last_storage
		+(input_from_melt+throughfall)*ti.get_dur()
		-  this->mod_etp->get_fluxes("ETR_Surface_water",ti)*ti.get_dur()
		-  real_infiltration;
		
	if ((budget<-0.01)||(budget>0.01)) err::err2(  "Mod_Surface_water_simple::compute: Budget_is_not_0.!");
	
	if(this->get_states("Surface_Storage", end)<0.001) 
		err::err3(  "Mod_Surface_water_simple::compute: Interception_Storage<0");
	return 0;
}
